<template>
  <img
    class="verify_code"
    :class="{ loading: loading }"
    ref="verifyCode"
    @click="refreshVerifyCode"
    :src="loading ? loadingImage : verifyCodeSrc"
    width="120px"
    height="40px"
    alt="验证码"
  />
</template>

<script setup>
import { ref, defineExpose, onMounted } from "vue";
import { debounce } from "lodash";
import authApi from "@/apis/common.js";
import { message } from "@/utils/message";

const verifyCodeSrc = ref("");
const captchaKey = ref("");
const loading = ref(true); // 加载状态
const loadingImage = "/src/assets/loading-2.gif"; // 你可以使用自己的加载占位图片
const emit = defineEmits(["updateCaptcha"]);

const refreshVerifyCode = () => {
  refresh();
};

const refresh = () => {
  getCaptchImg();
};

const getCaptchImg = debounce(async () => {
  loading.value = true; // 请求开始时设置为加载状态
  authApi
    .getCaptch()
    .then((res) => {
      verifyCodeSrc.value = res.data.captcha;
      captchaKey.value = res.data.captcha_key;
      emit("updateCaptcha", { key: captchaKey.value });
    })
    .catch((e) => {
      message(e.message, { type: "error" });
    })
    .finally(() => {
      loading.value = false; // 请求结束后关闭加载状态
    });
}, 300);

onMounted(async () => {
//   await getCaptchImg();
});

defineExpose({ refresh });
</script>
<style lang="less">
.loading {
  width: 20px;
  height: 20px;
}
</style>